/**
 * @FileName: AddDeviceActivity.java
 * @Package:com.bdtop.dbl.ui.activities.device
 * @Description: TODO
 * @author: MingjunLi
 * @date:2014-9-15
 * @version V1.0
 */

package com.bdtop.dbl.ui.activities.device;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.bdtop.dbl.BaseActivity;
import com.bdtop.dbl.DBLApplication;
import com.bdtop.dbl.R;
import com.bdtop.dbl.model.DeviceInfo;
import com.bdtop.dbl.server.ServerApiFactory;
import com.bdtop.dbl.server.response.AllDeviceInfoResponse;
import com.bdtop.dbl.server.response.BaseResponse;
import com.bdtop.dbl.thirdparty.asynchttp.RequestCallback;
import com.bdtop.dbl.ui.activities.main.MainActivity;
import com.bdtop.dbl.ui.view.TitleBar;
import com.bdtop.dbl.utils.Constants;
import com.bdtop.dbl.utils.DBLDebug;
import com.bdtop.dbl.utils.NetworkUtils;
import com.bdtop.dbl.utils.Preferences;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName: AddDeviceInfoActivity
 * @Description: TODO
 * @author: wangpeng
 * @date:2014-10-10
 */
public class DeviceAddActivity extends BaseActivity {

	private TitleBar mTitleBar;

	private static final String EXTRA_QR_CODE = "qr_code";

	public static final void launch(Context context, String qrCode) {
		Intent intent = new Intent(context, DeviceAddActivity.class);
		intent.putExtra(EXTRA_QR_CODE, qrCode);
		((Activity) context).startActivityForResult(intent, MainActivity.ADD_DEVICE_FROM_MAIN);
	}

	@Override protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_add_device_info);
		super.onCreate(savedInstanceState);

		initViews();
		loadData();
	}

	String deviceIMEI;

	@SuppressLint("SimpleDateFormat") private void loadData() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		String currentTime = sdf.format(new Date(System.currentTimeMillis()));
		txTime.setText(currentTime);

		String qrCode = getIntent().getStringExtra(EXTRA_QR_CODE);
		deviceIMEI = qrCode;
		txDeviceIMEI.setText(deviceIMEI);

		if (!qrCode.matches(Constants.VALIDATE_IMEI)) {
			showWrongDialog();
		}
	}

	private void showWrongDialog() {
		final Dialog d = new Dialog(this, R.style.Theme_Light_NoTitle_Dialog);
		d.setCancelable(false);
		d.setCanceledOnTouchOutside(false);

		View view = LayoutInflater.from(this).inflate(R.layout.dialog_confirm_2, null);
		TextView txMessage = (TextView) view.findViewById(R.id.tx_message);
		txMessage.setText(R.string.error_imei);

		view.findViewById(R.id.btn_confirm).setVisibility(View.GONE);
		view.findViewById(R.id.btn_divider).setVisibility(View.GONE);

		Button btnCancel = (Button) view.findViewById(R.id.btn_cancel);
		btnCancel.setText(R.string.ok_ikown2);
		btnCancel.setOnClickListener(new OnClickListener() {

			@Override public void onClick(View arg0) {
				d.dismiss();
				DeviceAddActivity.this.finish();
			}
		});

		d.setContentView(view);
		d.show();
	}

	// private String convertVendorValue(String vendor) {
	// String[] vendors = getResources().getStringArray(R.array.vendors);
	// if ("02".equals(vendor)) {
	// return vendors[1];
	// }
	// return vendors[0];
	// }

	private TextView txTime;
	// private TextView txVendor;
	private TextView txDeviceIMEI;

	private void initViews() {
		mTitleBar = (TitleBar) findViewById(R.id.title_bar);
		mTitleBar.setTitle(R.string.add_device_title);
		mTitleBar.setBelongActivity(this);

		txTime = (TextView) findViewById(R.id.tx_time);
		// txVendor = (TextView) findViewById(R.id.tx_vendor);
		txDeviceIMEI = (TextView) findViewById(R.id.tx_device_imei);

		findViewById(R.id.ok_btn).setOnClickListener(new OnClickListener() {
			@Override public void onClick(View view) {
				String sign = Preferences.getLoginSign(getApplicationContext());
				String IMEI = txDeviceIMEI.getText().toString();
				setAndShowWaitingMessage(R.string.waiting_add);
				ServerApiFactory.getApiImpl().deviceAdd(sign, IMEI, deviceAddCallback);
			}
		});
	}

	private RequestCallback deviceAddCallback = new RequestCallback() {
		@Override public void onSuccess(String rawData, Object response) {
			clearAndHiddenWaitingMessage();
			BaseResponse deviceAddResponse = (BaseResponse) response;

			String status = deviceAddResponse.getStatus();
			String desc = deviceAddResponse.getDesc();

			showToast(desc);
			if (Constants.REQUEST_SUCCESS.equals(status)) {
				getAllDeviceInfo();
			}
		}

		@Override public void onError(int statusCode, Throwable e, String rawData) {
			if (NetworkUtils.isNetConnect(getApplicationContext())) {
				showToast(R.string.oper_error);
			} else {
				showToast(R.string.net_error);
			}
			clearAndHiddenWaitingMessage();
		}
	};

	public void getAllDeviceInfo() {
		DBLDebug.logd("add device to re get all device info");

		setAndShowWaitingMessage(R.string.wating_get_device_list);

		String sign = Preferences.getLoginSign(getApplicationContext());
		ServerApiFactory.getApiImpl().getAllDeviceInfo(sign, new RequestCallback() {

			@Override public void onSuccess(String rawData, Object response) {
				clearAndHiddenWaitingMessage();
				AllDeviceInfoResponse adir = (AllDeviceInfoResponse) response;
				String status = adir.getStatus();
				if (Constants.REQUEST_SUCCESS.equals(status)) {
					if (adir.device_info != null) {
						DBLApplication.getInstance().deviceInfoList = adir.device_info;
						for (DeviceInfo di : DBLApplication.getInstance().deviceInfoList) {
							if (di.imei.equals(deviceIMEI)) {
								DBLApplication.getInstance().currentDi = di;
								break;
							}
						}
					}

					showActionDialog();
				}
			}

			@Override public void onError(int statusCode, Throwable e, String rawData) {
				if (NetworkUtils.isNetConnect(getApplicationContext())) {
					showToast(R.string.oper_error);
				} else {
					showToast(R.string.net_error);
				}
				clearAndHiddenWaitingMessage();
			}
		});
	}

	private Dialog mDialog;

	private void showActionDialog(){
            View content = LayoutInflater.from(this).inflate(R.layout.dialog_select_2_3, null);
            content.findViewById(R.id.tx_location).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                	MainActivity.launch(DeviceAddActivity.this,MainActivity.ACTION_LOCATION);
                	mDialog.dismiss();
                }
            });

            content.findViewById(R.id.tx_ble).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                	Preferences.saveRebindImei(DeviceAddActivity.this, deviceIMEI);
                	MainActivity.launch(DeviceAddActivity.this,MainActivity.ACTION_BLE_RESEARCH);
                	mDialog.dismiss();
                }
            });
            
            content.findViewById(R.id.tx_look).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View arg0) {
                	DeviceAddActivity.this.setResult(RESULT_OK);
                    DeviceAddActivity.this.finish();
                    mDialog.dismiss();
                }
            });

            mDialog = new Dialog(this, R.style.Theme_Light_NoTitle_Dialog);

            mDialog.setContentView(content);
            mDialog.setCanceledOnTouchOutside(false);
            mDialog.setCancelable(false);
            mDialog.show();
    }
}
